<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2022/6/17
 * Time: 16:41
 */
namespace app\job;

use think\queue\Job;
use think\Db;
use app\common\service\ZhiyuanService;

class ZhiyuanCache
{
    /**
     * fire方法是消息队列默认调用的方法
     * @param Job            $job      当前的任务对象
     * @param array|mixed    $data     发布任务时自定义的数据
     */
    public function fire(Job $job, $data)
    {
        //....这里执行具体的任务
        if($this->jobDone($data))
        {
            print("zhiyuan_end_".$data[0].'_'.$data[1]."_".date('Y/m/d H:i:s'));
            $job->delete();
            
        }else{
            $job->release(3); //$delay为延迟时间
        }

        if ($job->attempts() > 10) {
            //通过这个方法可以检查这个任务已经重试了几次了
			$job->delete();
        }

        //如果任务执行成功后 记得删除任务，不然这个任务会重复执行，直到达到最大重试次数后失败后，执行failed方法
        // $job->delete();

        // 也可以重新发布这个任务
        // $job->release($delay); //$delay为延迟时间

    }

    public function failed($data)
    {

        // ...任务达到最大重试次数后，失败了
    }

    public function jobDone($data)
    {
        print("zhiyuan_start_".$data[0].'_'.$data[1]."_".date('Y/m/d H:i:s'));
		
		$user_id = !empty($data[0])?$data[0]:0;
		$province_id = !empty($data[1])?$data[1]:0;
		if(empty($user_id) || empty($province_id)){
			setLog('zhiyuan_cache','user_id province_id 为空:'.$data[0].'_'.$data[1]);
			return true;
		}
		try{
			
			$result = ZhiyuanService::get_data_cache($user_id,$province_id);
			if($result[0] != 200){
				throw new \Exception($result[1]??'error',-1);
			}
			$data_res = $result[1];
			Cache('school_'.$user_id,$data_res);
			
			
			$all_nums = 0;
			$chong_nums = 0;
			$wen_nums = 0;
			$bao_nums = 0;
			$data_level = [];
			foreach($data_res as $k=>$v){
				$dengxiao_weicha = $v['dengxiao_weicha'];
				if($dengxiao_weicha>4000){//大于75%
					$bao_nums++;
				}elseif($dengxiao_weicha>-1 && $dengxiao_weicha<=4000){//大于46%,小于等于75%，
					$wen_nums++;
				}else{
					$chong_nums++;
				}
				$all_nums++;
			}
			$level_nums = array('all_nums'=>$all_nums,'chong_nums'=>$chong_nums,'wen_nums'=>$wen_nums,'bao_nums'=>$bao_nums);	
			Cache('level_nums_'.$user_id,$level_nums);
			
			
		}catch(\Exception $e){
			setLog('zhiyuan_cache','出错:'.$e->getMessage());
			return false;
		}	
		setLog('zhiyuan_cache','成功:'.$data[0].'_'.$data[1]);
		return true;
    }

}